using System;
using Sirenix.OdinInspector;
using Tools.UI.InputEvent;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Tools.UI
{
    public class OnDragPosSetter : MonoBehaviour
    {
        [SerializeField] OnUIDragPenetrate dragPenetrate;
        [SerializeField] RectTransform positionRectParent;
        [SerializeField] private RectTransform positionRect;
        
        [SerializeField] bool endRecoverPosition = false;
        [SerializeField] [ShowIf("endRecoverPosition")]Vector2 endPosition = Vector2.zero;
        private void Awake()
        {
            dragPenetrate.OnDragReady.AddListener(OnDragReadyFunc);
            dragPenetrate.OnDragging.AddListener(OnDraggingFunc);
            dragPenetrate.OnDragEnd.AddListener(OnDragEndFunc);
        }

        void OnEnable()
        {
            if (endRecoverPosition)
            {
                positionRect.anchoredPosition = endPosition;
            }
        }
        
        private void OnDragReadyFunc(OnUIDrag onDrag,PointerEventData eventData)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(positionRectParent, eventData.position, eventData.pressEventCamera, out Vector2 localPoint);
            positionRect.anchoredPosition = localPoint;
        }
        
        private void OnDraggingFunc(OnUIDrag onDrag, PointerEventData eventData)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(positionRectParent, eventData.position, eventData.pressEventCamera, out Vector2 localPoint);
            positionRect.anchoredPosition = localPoint;
        }

        private void OnDragEndFunc(OnUIDrag onDrag, PointerEventData eventData)
        {
            if (endRecoverPosition)
            {
                positionRect.anchoredPosition = endPosition;
            }
        }

#if UNITY_EDITOR
        private void Reset()
        {
            dragPenetrate = GetComponent<OnUIDragPenetrate>();
        }
#endif
    }
}
